/* eslint-disable prefer-destructuring */
/* eslint-disable no-undef */

const LOG_ERR_URL = '/log-trace/v2/user/event'

const pjson = require('/package.json')
let platform = pjson.name
// #ifdef H5
platform = `${platform}-h5`
// #endif

// #ifndef H5
platform = `${platform}-mp`
// #endif

// 错误日志上传
export function postLog(response, url, params, method) {
  let pathUrl = url
  try {
    let s = url
    if (method === 'GET') {
      s = pathUrl.split('?')
      pathUrl = s[0]
      params['?'] = s[1]
    }
  } catch (e) {
    console.warn(e)
  }
  const data = [{
    primaryKey: getMobile(),
    appId: '99',
    curTime: new Date().getTime(),
    eventId: pathUrl,
    eventType: 'server_error',
    platform,
    eventAttr: {
      url,
      params,
      responseMessage: response.msg,
    },
  }]
  const LOG_ERR = `${getApp().globalData.logHost}${LOG_ERR_URL}`
  uni.request({
    method: 'POST',
    url: LOG_ERR,
    data,
  })
}

// 日志上传
export function postClientLog(eventAttr) {
  const data = [{
    primaryKey: getMobile(),
    appId: '99',
    curTime: new Date().getTime(),
    eventId: 'client_error',
    eventType: 'client_error',
    platform,
    eventAttr, // 特殊日志上传，关键字放这里边
  }]
  const LOG_ERR = `${getApp().globalData.logHost}${LOG_ERR_URL}`
  uni.request({
    method: 'POST',
    url: LOG_ERR,
    data,
  })
}

function getMobile() {
  const loginData = uni.getStorageSync('loginData')
  let result = ''
  if (loginData) {
    result = loginData.match(/mobile":"(\d{11})/)
    return result ? result[1] : ''
  }
  return result
}
